from flask import views
from flask import request
from flask import Blueprint
from config import DB_URL
from sqlalchemy import create_engine
import json
from flask import make_response
import math

main_bp = Blueprint("main", __name__, url_prefix='')

engine = create_engine(DB_URL, pool_size=8, pool_recycle=60 * 10)


class MainView(views.MethodView):
    def get(self):
        return "Hello World!"


class PostsView(views.MethodView):
    def get(self):
        page = request.args.get('page')
        print("page ==== " + page)
        if page is None:
            page = 0
        else:
            if page.isdigit():
                page = int(page)
                if page > 0:
                    page = page - 1
            else:
                page = 0
        result = engine.execute(
            "select id, post_title, post_content, post_content_filtered, guid, post_date from demon_posts where post_type='post' AND post_status='publish' ORDER BY id DESC LIMIT {} OFFSET {}".format(
                10, page * 10))
        post_arr = result.all()

        strSql = " select count(*) as sum from demon_posts where post_type='post' AND post_status='publish'"
        count_list = engine.execute(strSql).all()
        count = 0
        if count_list:
            count = count_list[0][0]

        all_page = count / 10
        # print(all_page)

        isEnd = 1
        if all_page - 1 > page:
            isEnd = 0
        post_list = []
        for item in post_arr:
            time = item[5]
            dic = {
                "post_id": int(item[0]),
                "post_title": item[1],
                "post_content": item[2],
                "post_content_filtered": item[3],
                "guid": item[4],
                "post_date": time.strftime('%Y-%m-%d'),
            }
            post_list.append(dic)
            # print(dic)
        rst = make_response(json.dumps({'data': post_list, "isEnd": str(isEnd)}, ensure_ascii=False))
        rst.headers['Access-Control-Allow-Origin'] = '*'
        return rst, 200


class PostsPageView(views.MethodView):
    def get(self):
        strSql = " select count(*) as sum from demon_posts where post_type='post' AND post_status='publish'"
        count_list = engine.execute(strSql).all()
        count = 0
        if count_list:
            count = count_list[0][0]

        all_page = count / 10

        rst = make_response(json.dumps({'data': {'page': math.ceil(all_page), 'count': count}}, ensure_ascii=False))
        rst.headers['Access-Control-Allow-Origin'] = '*'
        return rst, 200


main_bp.add_url_rule("/", view_func=MainView.as_view('main'))
main_bp.add_url_rule("/posts/", view_func=PostsView.as_view('posts'))
main_bp.add_url_rule("/posts/count/", view_func=PostsPageView.as_view('posts_count'))
